package hydrap2p.proxy.manager;

import hydrap2p.ServiceLocation;

import java.util.Map;
import java.util.TreeMap;

public class DoubleMap<K1,K2,V> {

	private Map<K1, Map<K2,V>> connections;
	
	public DoubleMap()
	{
		connections=new TreeMap<K1, Map<K2,V>>();
	}
	
	public V get(K1 k1, K2 k2)
	{
		Map<K2,V> inner;
		synchronized(connections)
		{
			inner=connections.get(k1);
		}
		if (inner==null)
			return null;
		
		synchronized(inner)
		{
			return inner.get(k2);
		}
	}
	
	public void put(K1 k1, K2 k2, V v)
	{
		Map<K2,V> inner;
		synchronized(connections)
		{
			inner=connections.get(k1);
			if (inner==null)
			{
				inner=new TreeMap<K2,V>();
				connections.put(k1, inner);
			}
		}
		synchronized(inner)
		{
			inner.put(k2, v);
		}
	}
	
	public void remove(K1 k1, K2 k2)
	{
		Map<K2,V> inner;
		synchronized(connections)
		{
			inner=connections.get(k1);
		}
		if (inner==null)
			return;
		
		synchronized(inner)
		{
			inner.remove(k2);
			if (inner.size()==0)
			{
				synchronized(connections)
				{
					connections.remove(k1);
				}
			}
		}
	}
}
